package org.example.skytool.es.index;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.example.exception.EsException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class EsIndexUtil {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    public void createIndex(String name, String mappingTemplate) {
        try {
            CreateIndexRequest request = new CreateIndexRequest(name);
            request.source(mappingTemplate, XContentType.JSON);
            restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new EsException(e.getMessage());
        }
    }

    public void deleteIndex(String name)  {
        try {
            DeleteIndexRequest request = new DeleteIndexRequest(name);
            restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new EsException(e.getMessage());
        }
    }

    public boolean existsIndex(String name) {
        try {
            GetIndexRequest request = new GetIndexRequest(name);
            return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new EsException(e.getMessage());
        }
    }



}
